var CustomMaterial = require('CustomMaterial');
//
cc.Class({
    extends: cc.Component,

    _getShaderName(){
        return '';
    },

    properties: {
        sprite:{
            default:null,
            type:cc.Sprite,
            tooltip:'效果基于sprite发挥'
        }
    },

    onToggleEvent(toggle){
        this.enabled = toggle.isChecked;
    },

    onLoad() {
        this.sprite = this.sprite || this.getComponent(cc.Sprite);
    },

    onEnable() {
        this.applyShader(this._getShaderName());
    },

    onDisable() {
        this.sprite.setState(cc.Sprite.State.NORMAL);
        //
        this._postUnapplyShader();
    },

    updateMat(dt){

    },

    update(dt) {
        if (this._shaderObject && this._shaderObject.update) {
            this._shaderObject.update(this.sprite, this.material, dt);
            //
            this.updateMat(dt);
        }
    },
    /**
     * 设置材质的参数
     * @param {} params 参数列表
     */
    setMaterialParams(params){
        if (this.material == null)
            return;
        //
        for(var k in params){
            this.material.setParamValue(k, params[k]);
        }
    },

    /**
     * 启用Shader
     */
    applyShader(shaderName) {

        this._preApplyShader();

        let shaderObject = CustomMaterial.getShader(shaderName);

        if (shaderObject == null) {
            console.error('shader: ' + name + ' not found.');
            return;
        }
        //
        this._applyShader(shaderObject);
        //

        this._postApplyShader();
    },
    /**
     * 子类可以在正式应用shader前做一些工作
     */
    _preApplyShader(){

    },
    /**
     * 子类可以在应用shader后做一些工作
     */
    _postApplyShader(){

    },
    /**
     * 禁用效果后调用
     */
    _postUnapplyShader(){

    },

    _applyShader(shaderObject) {
        this._shaderObject = shaderObject;
        //
        let sprite = this.sprite;
        let params = this._shaderObject.params;
        let defines = this._shaderObject.defines;
        let material = sprite.getMaterial(this._shaderObject.name);

        if (!material) {
            material = new CustomMaterial(this._shaderObject.name, params, defines || []);
            sprite.setMaterial(this._shaderObject.name, material);
        }
        this.material = material;

        sprite.activateMaterial(this._shaderObject.name);

        //设置Shader参数初值
        if (params) {
            params.forEach((item) => {
                if (item.defaultValue !== undefined) {
                    material.setParamValue(item.name, item.defaultValue);
                }
            });
        }

        // if (this._shaderObject.start) {
        //     this._shaderObject.start(sprite, material);
        // }

    },
    // tools

    _colorToQuat(color){
        return {
            x:color.r/255.0,
            y:color.g/255.0,
            z:color.b/255.0,
            w:color.a/255.0
        };
    }
});
